<template>
  <div class="layui-form layui-form-pane layui-tab-item layui-show">
    <div class="layui-form-item">
      <div class="avatar-add">
        <p>建议尺寸168*168，支持jpg、png、gif，最大不能超过50KB</p>
        <label for="uploadFile" class="layui-btn upload-img">
          <i class="layui-icon">&#xe67c;</i>上传头像
        </label>
        <input type="file" accept="image/jpeg, image/png, image/gif" id="uploadFile" @change="upload">
        <img :src="pic">
        <span class="loading"></span>
      </div>
    </div>
  </div>
</template>
<script>
import { uploadImg } from '@/api/content';
import { updateUserInfo } from '@/api/user';
import config from '@/config';

export default {
  name: 'PicUpload',
  data () {
    return {
      pic: this.$store.state.userInfo ? config.baseURL.dev + this.$store.state.userInfo.pic : 'https://tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg',
      formData: null
    };
  },
  methods: {
    upload (e) {
      // console.log(e)
      const file = e.target.files;
      if (file.length > 0) {
        const formData = new FormData();
        formData.append('file', file[0]);
        // 将上传结果保存，方便接口调用
        this.formData = formData;

        uploadImg(this.formData).then(res => {
          if (res.code === 200) {
            updateUserInfo({ pic: res.data }).then(res => {
              if (res.code === 200) {
                this.$alert('更新用户头像成功');
                this.$store.commit('setUserInfo', {
                  ...this.$store.state.userInfo,
                  pic: res.data
                });
              }
            });
          };
          this.pic = config.baseURL.dev + res.data;
        });
      }
    }
  }
};
</script>
<style scoped lang="scss">
#uploadFile {
  display: none;
}
</style>
